"""
知识库工具函数
"""
import os
from datetime import datetime
from django.conf import settings

def get_knowledge_files_dir():
    """获取知识库文件存储目录"""
    knowledge_dir = os.path.join(settings.BASE_DIR, 'knowledge_files')
    if not os.path.exists(knowledge_dir):
        os.makedirs(knowledge_dir)
    return knowledge_dir

def generate_date_based_filename(original_filename):
    """
    生成基于日期的文件名
    格式：YYYYMMDD-XXX.ext
    
    Args:
        original_filename: 原始文件名
        
    Returns:
        str: 新的文件名
    """
    file_extension = os.path.splitext(original_filename)[1]
    today = datetime.now().strftime('%Y%m%d')
    
    # 获取知识库文件目录
    knowledge_dir = get_knowledge_files_dir()
    
    # 查找今天已有的文件数量
    existing_files = []
    for filename in os.listdir(knowledge_dir):
        if filename.startswith(today + '-') and filename.endswith(file_extension):
            try:
                # 提取序号
                name_part = filename.replace(file_extension, '')  # 去掉扩展名
                number_part = name_part.split('-')[1]            # 获取序号部分
                if number_part.isdigit():
                    existing_files.append(int(number_part))
            except:
                continue
    
    # 计算下一个序号
    if existing_files:
        next_number = max(existing_files) + 1
    else:
        next_number = 1
    
    # 生成新文件名
    return f"{today}-{next_number:03d}{file_extension}"

def get_file_info(file_path):
    """
    获取文件信息
    
    Args:
        file_path: 文件绝对路径
        
    Returns:
        dict: 文件信息字典
    """
    if not os.path.exists(file_path):
        return None
        
    stat_info = os.stat(file_path)
    file_size = stat_info.st_size
    
    # 格式化文件大小
    if file_size < 1024:
        size_str = f"{file_size} B"
    elif file_size < 1024 * 1024:
        size_str = f"{file_size / 1024:.1f} KB"
    else:
        size_str = f"{file_size / (1024 * 1024):.1f} MB"
    
    return {
        'size': file_size,
        'size_display': size_str,
        'exists': True
    }

def cleanup_orphaned_files():
    """
    清理孤立的文件（数据库中没有记录但文件系统中存在的文件）
    """
    from .models import KnowledgeBase
    
    knowledge_dir = get_knowledge_files_dir()
    db_files = set(KnowledgeBase.objects.exclude(file_path='').values_list('file_path', flat=True))
    
    orphaned_files = []
    
    for filename in os.listdir(knowledge_dir):
        file_path = os.path.join(knowledge_dir, filename)
        if os.path.isfile(file_path) and filename not in db_files:
            orphaned_files.append(filename)
    
    return orphaned_files
